package org.example.uhy.repository.config;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.example.uhy.supports.utils.LocalDateTimeUtils;

import java.sql.*;
import java.time.LocalDate;
import java.time.ZoneId;

public class LocalDateTypeHandler extends BaseTypeHandler<LocalDate> {
    ZoneId zoneId;

    public LocalDateTypeHandler(ZoneId zoneId) {
        this.zoneId = zoneId;
    }

    public void setNonNullParameter(PreparedStatement ps, int i, LocalDate parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter);
    }

    public LocalDate getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return toLocalDate(rs.getObject(columnName));
    }

    public LocalDate getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toLocalDate(rs.getObject(columnIndex));
    }

    public LocalDate getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toLocalDate(cs.getObject(columnIndex));
    }

    private LocalDate toLocalDate(Object ts) throws SQLFeatureNotSupportedException {
        if (ts == null) {
            return null;
        }
        if (ts instanceof LocalDate) {
            return (LocalDate) ts;
        } else if (ts instanceof Timestamp) {
            return ((Timestamp) ts).toLocalDateTime().toLocalDate();
        } else if (ts instanceof Date) {
            return ((Date) ts).toLocalDate();
        } else if (ts instanceof String) {
            return LocalDateTimeUtils.parseDate((String) ts);
        } else {
            throw new SQLFeatureNotSupportedException();
        }
    }
}